package debut.peinture;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Gallery;

public class DroidPaintings extends Activity implements Constantes {
//	private static final int NOMBRE_ESSAIS = 20;
	private static final int CODE_RETOUR_TTS = 50;
    public DataBaseHelper monDbHelper = null;
    public Cursor curseur = null ;
//  private Activity activite = this;
    public String categChoisie = null;
    public String valeurChoisie = null;
    public String valeurRepChoisie = null;
    public Integer entierChoisi = -1;
    public boolean okParler = false;
    private Integer ongletActuel = 0;
    private boolean baseRecopiee = false;
    public Integer indexencours = 0 ;
    public TextToSpeech monTts;
    
    protected void onActivityResult(int codeRequete, int codeRetour, Intent donnees) {
        if (codeRequete == CODE_RETOUR_TTS) {
            if (codeRetour == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
            	monTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
					@Override
					public void onInit(int status) {
						okParler = true;
					}
            	});
            } else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle etatSauve) {
        super.onCreate(etatSauve);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//      setProgressBarIndeterminateVisibility(true);
        
        Configuration conf = getResources().getConfiguration();
//      Configuration conf = new Configuration();
//		conf.setToDefaults();
//		String langue = conf.locale.toString();
//		((TextView) findViewById(R.id.textelangage)).setText(langue + "\n" + getResources().getString(R.string.traduction));
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, CODE_RETOUR_TTS);
		if(okParler) {
			monTts.setLanguage(conf.locale);
		}
        
//        ((TextView) findViewById(R.id.textecredits)).setText(getResources().getString(R.string.source) + " :\n" 
//        		+ "http://commons.wikimedia.org");
        
        monDbHelper = new DataBaseHelper(this.getBaseContext(), NOM_DB, null, 1);
        try {
        	monDbHelper.createDataBase();
        } catch (IOException ioe) {
        	throw new Error("Erreur de création de la base de données");
        }
        try {
        	monDbHelper.openDataBase();
        } catch (SQLException sqle) {
        	throw sqle;
        }      
        
        String finsql = this.getBaseContext().getResources().getString(R.string.requetetoutfrom);
    	if (etatSauve != null) {
        	super.onRestoreInstanceState(etatSauve);
        	indexencours = etatSauve.getInt("index");
        	categChoisie = etatSauve.getString("categorie");
        	valeurChoisie = etatSauve.getString("valeur");
        	valeurRepChoisie = etatSauve.getString("valeurRep");
        	entierChoisi = etatSauve.getInt("entier");
        	ongletActuel = etatSauve.getInt("tab");
        	baseRecopiee = etatSauve.getBoolean("base");
        	finsql = retournefinsql();
        }
    	curseur = monDbHelper.maDataBase.rawQuery(this.getBaseContext().getResources().getString(R.string.requetetout) + " " 
    			+ finsql, null);
//    	if(ecranActuel == ECRAN_IMAGE) {
//    		((ViewAnimator) findViewById(R.id.navig)).showNext();
//			remplirGalerie(this.getBaseContext());
//			boutonsDisparaissent();
//    	}
//    	if(ecranActuel == ECRAN_CATEG) {
//    		((ViewAnimator) findViewById(R.id.navig)).showNext();
//    		((ViewAnimator) findViewById(R.id.navig)).showNext();
//    		mettreCategories();
//    		((TextView)findViewById(R.id.idaffichecateg)).setText(finsql);
//    	}
    	setContentView(R.layout.mainfrag);
//    	findViewById(R.id.idbtndroite).setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				setProgressBarIndeterminateVisibility(true);
//				((ViewAnimator) findViewById(R.id.navig)).showNext();
//				ecranActuel = ECRAN_IMAGE;
//		    	String requete = v.getContext().getResources().getString(R.string.requetetout);
//		        curseur = monDbHelper.maDataBase.rawQuery(requete,null);
//		        remplirGalerie(v.getContext());
//		        boutonsDisparaissent();
//	        	setProgressBarIndeterminateVisibility(false);
//			}
//    	});
/*
		((Gallery)findViewById(R.id.idfond)).setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View vueItem, int position, long id) {
//				boutonsDisparaissent();
				final PopupWindow fenetre = new PopupWindow(vueItem.getContext());
				fenetre.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
				fenetre.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
				fenetre.setTouchable(true);
				fenetre.setFocusable(true);
				fenetre.setOutsideTouchable(true);
				fenetre.setBackgroundDrawable(new BitmapDrawable());
				LayoutInflater inflateur = (LayoutInflater) vueItem.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				ViewGroup racine = (ViewGroup) inflateur.inflate(R.layout.popup, null);
				fenetre.setContentView(racine);
//				fonctions sur clic des boutons
				for(int i = 0, icount = racine.getChildCount() ; i < icount ; i++) {
					View vue = racine.getChildAt(i);
					if(vue instanceof TableRow) {
						TableRow rangee = (TableRow) vue;
						for(int j = 0, jcount = rangee.getChildCount() ; j < jcount ; j++) {
							View item = rangee.getChildAt(j);
							if(item instanceof ImageButton) {
								ImageButton ib = (ImageButton) item;
								ib.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										ImageButton b = (ImageButton) v;
										String[] colonnes = v.getResources().getStringArray(R.array.colonnes);
										Integer numbouton = b.getId();
										switch(numbouton) {
										case R.id.btngrille:
											((ViewAnimator) findViewById(R.id.navig)).showNext();
											((ViewAnimator) findViewById(R.id.navig)).showNext();
											GridView vuegrid = (GridView) findViewById(R.id.vuegrille);
											vuegrid.setSelection(indexencours);
											break;
										case R.id.btntri:
											categChoisie = null;
											((ViewAnimator) findViewById(R.id.navig)).showNext();
//											ecranActuel = ECRAN_CATEG;
//											mettreCategories();
											break;
										case R.id.btnrech:
											onSearchRequested();
											break;
										case R.id.btninfo:
											Gallery galerie = (Gallery) findViewById(R.id.idfond);
											int posi = galerie.getSelectedItemPosition();
											curseur.moveToPosition(posi);
											String pagewiki = curseur.getString(curseur.getColumnIndex(colonnes[6]));
									    	Uri uripw = Uri.parse(pagewiki);
									    	Intent lancew = new Intent(Intent.ACTION_VIEW,uripw);
//									    	lance.putExtra(SearchManager.QUERY, nom + " " + titre);
									    	startActivity(lancew);
											break;
										case R.id.btnpartage:
											String titre = curseur.getString(curseur.getColumnIndex(colonnes[1]));
								    		String nom = curseur.getString(curseur.getColumnIndex(colonnes[2]));
								    		String lien = curseur.getString(curseur.getColumnIndex(colonnes[6]));
											Intent lancep = new Intent(Intent.ACTION_SEND)
												.putExtra(Intent.EXTRA_TEXT, nom + "\n" + titre + "\n" + lien).setType("text/plain")
									   			.putExtra(Intent.EXTRA_SUBJECT, v.getContext().getResources().getString(R.string.app_name));
									    	startActivityForResult(Intent.createChooser(lancep, ""),0);
									    	break;
										default:
											break;
										}
										fenetre.dismiss();
									}
								});
							}
						}
					}
				}
//				affichage des boutons actions
				fenetre.setAnimationStyle(R.style.Animations_PopDownMenu);
				fenetre.showAsDropDown(vueItem,(vueItem.getWidth())/3,-2*(vueItem.getHeight())/3);
			}
		});
*/		
		// setup Action Bar for tabs
	    final ActionBar actionBar = getActionBar();
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    Fragment fraggalerie = getFragmentManager().findFragmentById(R.id.idfraggalerie);
	    Fragment fragdiapo = getFragmentManager().findFragmentById(R.id.idfragdiapo);
	    Fragment fraggrille = getFragmentManager().findFragmentById(R.id.idfraggrille);
	    Fragment fragcateg = getFragmentManager().findFragmentById(R.id.idfragcateg);
	    actionBar.addTab(actionBar.newTab().setText(R.string.menugalerie).setTabListener(new MonTabListener(fraggalerie)),0);
	    actionBar.addTab(actionBar.newTab().setText(R.string.menudiaporama).setTabListener(new MonTabListener(fragdiapo)),1);
	    actionBar.addTab(actionBar.newTab().setText(R.string.menugrille).setTabListener(new MonTabListener(fraggrille)),2);
//	    actionBar.setSelectedNavigationItem(0);
	    FragmentTransaction ftgal = getFragmentManager().beginTransaction();
	    ftgal.hide(fragdiapo);
	    ftgal.hide(fraggrille);
	    ftgal.hide(fragcateg);
		ftgal.commit();
		actionBar.setSelectedNavigationItem(ongletActuel);
//		setProgressBarIndeterminateVisibility(false);
    }
    
    private class MonTabListener implements ActionBar.TabListener {
        private Fragment monFragment;

        // Called to create an instance of the listener when adding a new tab
        public MonTabListener(Fragment fragment) {
        	monFragment = fragment;
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
//            ft.add(R.id.fragment_content, monFragment, null);
        	Fragment fraggalerie = getFragmentManager().findFragmentById(R.id.idfraggalerie);
        	Fragment fragdiapo = getFragmentManager().findFragmentById(R.id.idfragdiapo);
        	Fragment fraggrille = getFragmentManager().findFragmentById(R.id.idfraggrille);
        	Fragment fragcateg = getFragmentManager().findFragmentById(R.id.idfragcateg);
//        	ft.hide(fraggalerie);
//        	ft.hide(fragdiapo);
//    		ft.hide(fragcateg);
    		int p = tab.getPosition();
        	switch(p) {
        	case 0:
//        		FragmentTransaction ft = getFragmentManager().beginTransaction();
//        		ft.show(fraggalerie);
        		((FragGalerie) fraggalerie).remplirGalerie();
        		((Gallery)fraggalerie.getView().findViewById(R.id.idfond)).setSelection(indexencours);
//        		ft.commit();
        		break;
        	case 1:
//        		FragmentTransaction ft = getFragmentManager().beginTransaction();
//        		ft.show(fragdiapo);
            	((FragDiapo)fragdiapo).transitionTableau();
            	((FragDiapo)fragdiapo).lanceDiapo();
//        		ft.commit();
        		break;
        	case 2:
//        		FragmentTransaction ft = getFragmentManager().beginTransaction();
//        		ft.show(fragdiapo);
        		((FragGrille) fraggrille).remplirGrille();
//        		((GridView)fraggrille.getView().findViewById(R.id.vuegrille)).setSelection(indexencours);
//        		ft.commit();
        		break;
        	}
        	ft.show(monFragment);
        	ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        }

		@Override
		public void onTabReselected(Tab arg0, FragmentTransaction ft) {
			// TODO Auto-generated
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			ft.hide(monFragment);
			Fragment fragdiapo = getFragmentManager().findFragmentById(R.id.idfragdiapo);
			switch(tab.getPosition()) {
        	case 0:
        		break;
        	case 1:
        		((FragDiapo)fragdiapo).arreteDiapo();
        		break;
			}
		}

    }
    
    @Override
    public boolean onSearchRequested() {
//    	if(ecranActuel == ECRAN_IMAGE) {
//    		String[] colonnes = this.getResources().getStringArray(R.array.colonnes);
//    		String titre = curseur.getString(curseur.getColumnIndex(colonnes[1]));
//    		String nom = curseur.getString(curseur.getColumnIndex(colonnes[2]));
//    		startSearch(nom + " " + titre, false, null, false);
//    		Intent lance = new Intent();
//	    	lance.setAction(Intent.ACTION_WEB_SEARCH);
//	    	lance.putExtra(SearchManager.QUERY, nom + " " + titre);
//	    	startActivity(lance);
//    	}
        return true;
     }
    
    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onRestart() {
        super.onRestart();
    }
    
    @Override
    public void onPause() {
        super.onPause();
    }
    
    @Override
    public void onStop() {
        super.onStop(); 
    }
/*    
    private void boutonsDisparaissent() {
    	findViewById(R.id.idbtnsuivant).setVisibility(View.VISIBLE);
		findViewById(R.id.idbtnpreced).setVisibility(View.VISIBLE);
    	Animation animsuivant = AnimationUtils.loadAnimation(this, R.anim.disparait);
		animsuivant.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				findViewById(R.id.idbtnsuivant).setVisibility(View.INVISIBLE);
				findViewById(R.id.idbtnpreced).setVisibility(View.INVISIBLE);
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}

			@Override
			public void onAnimationStart(Animation animation) {
				
			}
		});
		findViewById(R.id.idbtnsuivant).setAnimation(animsuivant);
		Animation animpreced = AnimationUtils.loadAnimation(this, R.anim.disparait);
		findViewById(R.id.idbtnpreced).setAnimation(animpreced);
    }
*/    
    public String retournefinsql() {
    	String finsql = "";
    	String colonnepays = "";
    	String langue = getResources().getConfiguration().locale.getLanguage();
    	if(langue.equals(Locale.FRENCH.getLanguage())) {
    		colonnepays = "nom_fr";
    	} else {
    		colonnepays = "nom_en";
    	}
    	if(categChoisie != null ) {
    		if(categChoisie.contains(getResources().getStringArray(R.array.categories)[0])) {
				finsql = " from oeuvres, peintres where oeuvres.id_peintre = peintres._id and peintres." 
					+ getResources().getString(R.string.colonnestyle) + " = '" + valeurChoisie +"'";
			} else if(categChoisie.contains(getResources().getStringArray(R.array.categories)[1])) {
				finsql = " from oeuvres, peintres, pays where oeuvres.id_peintre = peintres._id and peintres.pays_id" 
					+ " = pays.id and pays." + colonnepays + " = '"	+ valeurChoisie +"'";
			} else if(categChoisie.contains(getResources().getStringArray(R.array.categories)[2])) {
				finsql = " from oeuvres, peintres where oeuvres.id_peintre = peintres._id and peintres.nom = '" 
					+ valeurChoisie +"'";
			} else if(categChoisie.contains(getResources().getStringArray(R.array.categories)[3])) {
				finsql = " from oeuvres, peintres where oeuvres.id_peintre = peintres._id and oeuvres.lieu = '" 
					+ valeurChoisie +"'";
			} else if(categChoisie.contains(getResources().getStringArray(R.array.categories)[4])) {
				finsql = " from oeuvres, peintres where oeuvres.id_peintre = peintres._id and oeuvres.annee = '" 
					+ valeurChoisie +"'";
			}
    	} else {
    		finsql = " from oeuvres, peintres where oeuvres.id_peintre = peintres._id";
    	}
		return finsql;
    }
    
    public class DataBaseHelper extends SQLiteOpenHelper {
        public SQLiteDatabase maDataBase; 
        private Context monContexte;

		public DataBaseHelper(Context contexte, String nom, CursorFactory usine, int version) {
			super(contexte, nom, usine, version);
			this.monContexte = contexte;
		}
		
		/**
	     * Creates a empty database on the system and rewrites it with your own database.
	     * */
	    public void createDataBase() throws IOException {
	    	boolean dbExist = checkDataBase();
	    	if(dbExist) {
	    		//recopie pour avoir la dernière version
	    		this.getReadableDatabase();
	    		if(baseRecopiee == false) {
	    			try {
	    				copyDataBase();
	    			} catch (IOException e) {
	    				throw new Error("Error copying database");
	    			}
	    		}
	    	} else {
	    		//By calling this method an empty database will be created into the default system path
	            //of your application so we are gonna be able to overwrite that database with our database.
	        	this.getReadableDatabase();
	        	if(baseRecopiee == false) {
	        		try {
	        			copyDataBase();
	        		} catch (IOException e) {
	        			throw new Error("Error copying database");
	        		}
	        	}
	    	}
	    }
	    
	    /**
	     * Check if the database already exist to avoid re-copying the file each time you open the application.
	     * @return true if it exists, false if it doesn't
	     */
	    private boolean checkDataBase() {
	    	SQLiteDatabase verifBD = null;
	    	try {
	    		String monChemin = CHEMIN_DB + NOM_DB;
	    		verifBD = SQLiteDatabase.openDatabase(monChemin, null, SQLiteDatabase.OPEN_READONLY);
	    	} catch(SQLiteException e) {
	    		//database does't exist yet.
	    	}
	    	if(verifBD != null) {
	    		verifBD.close();
	    	}
	    	return verifBD != null ? true : false;
	    }
	    
	    /**
	     * Copies your database from your local assets-folder to the just created empty database in the
	     * system folder, from where it can be accessed and handled.
	     * This is done by transfering bytestream.
	     * */
	    private void copyDataBase() throws IOException {
	    	//Open your local db as the input stream
	    	InputStream monEntree = monContexte.getAssets().open(NOM_DB);
	    	// Path to the just created empty db
	    	String FichierSortie = CHEMIN_DB + NOM_DB;
	    	//Open the empty db as the output stream
	    	OutputStream maSortie = new FileOutputStream(FichierSortie);
	    	//transfer bytes from the inputfile to the outputfile
	    	byte[] buffer = new byte[1024];
	    	int length;
	    	while ((length = monEntree.read(buffer))>0) {
	    		maSortie.write(buffer, 0, length);
	    	}
	    	//Close the streams
	    	maSortie.flush();
	    	maSortie.close();
//	    	maSortie.close();
	    	baseRecopiee = true;
	    }
	    
	    public void openDataBase() throws SQLException {
	    	//Open the database
	    	String monChemin = CHEMIN_DB + NOM_DB;
	    	maDataBase = SQLiteDatabase.openDatabase(monChemin, null, SQLiteDatabase.OPEN_READONLY);
	 
	    }
	    
	    @Override
		public synchronized void close() {
	    	if(maDataBase != null) maDataBase.close();
	    	super.close();
		}
 
		@Override
		public void onCreate(SQLiteDatabase db) {
						
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
						
		}
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
/*    	boolean result = super.onCreateOptionsMenu(menu);
    	menu.add(Menu.NONE, MENU_DIAPO, 0, getResources().getString(R.string.diaporama)).setIcon(android.R.drawable.ic_menu_gallery);
    	menu.add(Menu.NONE, MENU_PARAM, 1, getResources().getString(R.string.param)).setIcon(android.R.drawable.ic_menu_preferences);
    	menu.add(Menu.NONE, MENU_APROPOS, 2, getResources().getString(R.string.apropos)).setIcon(android.R.drawable.ic_menu_edit);*/
    	MenuInflater inflateur = getMenuInflater();
   	    inflateur.inflate(R.menu.actions, menu);
   	    return true;
    }
     
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.actionrecherche:
    		Fragment fragcateg = getFragmentManager().findFragmentById(R.id.idfragcateg);
    		((FragCateg)fragcateg).mettreCategories();
    		FragmentTransaction ftgal = getFragmentManager().beginTransaction();
    	    ftgal.show(fragcateg);
    		ftgal.commit();
    		break;
        case R.id.actionparametres:
        	Intent lanceconfig = new Intent();
	    	lanceconfig.setClassName("debut.peinture", "debut.peinture.Config");
	    	startActivity(lanceconfig);
        	break;
        case R.id.actionapropos:
//        	Uri uriap = Uri.parse("https://sites.google.com/site/bobygerm/applications-android/expo-peinture");
//        	Intent intentap = new Intent(Intent.ACTION_VIEW, uriap);
//        	startActivity(intentap);      	
//        	Intent lanceApplis = new Intent(Intent.ACTION_VIEW);
//        	String lienmarket = "market://details?id=debut.peinture";
//        	lien = "https://sites.google.com/site/bobygerm/applications-android/fortunesfr";
//        	lien = "market://details?id=debut.peinture";
//        	Uri u = Uri.parse(lienmarket);
//    		lanceApplis.setData(u);
//    		startActivity(lanceApplis);
    		// Create and show the dialog.
        	FragmentTransaction ftr = getFragmentManager().beginTransaction();
		    DialogFragment nouvFragment = new FragApropos();
		    nouvFragment.show(ftr, "apropos");
        	break;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    @Override 
    public void onSaveInstanceState(Bundle sauvEtat) {
    	sauvEtat.putInt("index", indexencours);
    	sauvEtat.putString("categorie", categChoisie);
    	sauvEtat.putString("valeur", valeurChoisie);
    	sauvEtat.putString("valeurRep", valeurRepChoisie);
    	sauvEtat.putInt("entier", entierChoisi);
    	sauvEtat.putInt("tab", getActionBar().getSelectedNavigationIndex());
    	sauvEtat.putBoolean("base", baseRecopiee);
    	super.onSaveInstanceState(sauvEtat);
    }
    
//    @Override
//    public Object onRetainNonConfigurationInstance() {
/*    	Bitmap b = null;
    	if(ecranAccueil == false) {
    		b = ( (BitmapDrawable) ( (ImageView)findViewById(R.id.idfond)).getDrawable()).getBitmap();
    	}
    	return b;*/
//    	return null;
//    }
}